package com.tjtt.tdm.visual.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.hibernate.Hibernate;

import com.opensymphony.xwork2.ActionContext;
import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.PubMethod;
import com.tjtt.tdm.exception.DaoException;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.visual.bean.VisualInfo;
import com.tjtt.tdm.visual.service.VisualService;

public class VisualAction extends BaseAction {
	private VisualService visualService;
	private VisualInfo visualEntity;
	private File picfile;
	private String visualid;
	

	public String getVisualid() {
		return visualid;
	}

	public void setVisualid(String visualid) {
		this.visualid = visualid;
	}
	
	public String initVisualdesignlist(){
		String floorinfotree = "";
		try {
			floorinfotree = getFloorinfotree();
			
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		this.getRequest().setAttribute("floorinfotree", floorinfotree);
		return "visualdesignlist";
	}

	public void GetVisualList()
	{
		try{ 
			String pId = getRequest().getParameter("pId");
			String type = getRequest().getParameter("type");
			Map<String, String> filterMap = getPagerMap();
			if(null!=pId&&!"".equals(pId)){
				filterMap.put("pId", pId);
			}
			if(null!=type&&!"".equals(type)){
				filterMap.put("type", type);
			}
			if(null!=getRequest().getParameter("visualId")&&!"".equals(getRequest().getParameter("visualId")))
				filterMap.put("visualId", getRequest().getParameter("visualId"));
			if(null!=getRequest().getParameter("notin")&&!"".equals(getRequest().getParameter("notin")))
				filterMap.put("notin", getRequest().getParameter("notin"));
			
			String[] viewArray = {"id","visualname","picaddress","remark","parentid"};
			String returnStr = "";
			
			//查询出所有数据
			PageResult result = visualService.GetVisualList(filterMap);
			returnStr = getColumnJson(result, viewArray);
			
			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void addVisual() throws IOException{
		PrintWriter out = getResponse().getWriter();
		try{
			ActionContext ac = ActionContext.getContext();
	        ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
			FileInputStream fis = new FileInputStream(picfile); 
			String url = sc.getRealPath("/") + File.separator + "visual" + File.separator + "picfile" + File.separator;
			String address = PubMethod.GetTimerName()+".jpg";
			FileOutputStream fos = new FileOutputStream(url+address); 
			byte[] buffer = new byte[1024]; 
			int len = 0; 
			while ((len = fis.read(buffer)) > 0) 
			{ 
				fos.write(buffer, 0, len);
			} 
			fos.close();
			fis.close();
			visualEntity.setPicaddress(address);
			visualEntity.setFilename("");
			visualEntity.setType(String.valueOf((Integer.parseInt(visualEntity.getType())+1)));
			visualService.saveobject(visualEntity);
			out.print("{\"result\":\"success\"}");
		}catch (Exception e) {
			out.print("{\"result\":\"error\"}");
			e.printStackTrace();
		}
	}
	
	/**
	 * 可视化动态加载人员、设备图片
	 * @throws IOException
	 */
	public void showVisualPic() throws IOException{
		PrintWriter out = PubMethod.GetPrintWriter();
		String id = getRequest().getParameter("id");
		String type = getRequest().getParameter("type");
		String path = "";
		try{
			if("equipment".equals(type)){
//				equipmentLibrary = visualService.queryEquipmentLibraryById(id);作废
				path = visualService.getEquipmentPath(id,"EQUIPPIC");
			}else if ("person".equals(type)){
//				users=visualService.findUsersById(Long.parseLong(id));
//				path = users.getImgAddress();
			}
			else if ("light".equals(type)){
				String light = visualService.getEquipmentPath(id,"rquipment_type");
				if (light.equals("")){
					path = "blue.png";
				}
				else if (light.equals("使用")){
					path = "green.png";
				}
				else if (light.equals("空闲")){
					path = "blue.png";
				}
				else if (light.equals("报废")){
					path = "black.png";
				}
				else if (light.equals("故障")){
					path = "red.png";
				}
				else if (light.equals("维修")){
					path = "yellow.png";
				}
				else if (light.equals("送检")){
					path = "grey.png";
				}
			}
			out.print(path);
		}catch (Exception e) {
			out.print("error");
			e.printStackTrace();
		}
	}
	
	
	//返回设备人员信息
	public void showEuipmentPersonPic() throws IOException{
		PrintWriter out = PubMethod.GetPrintWriter();
		String id = getRequest().getParameter("id");
		String userinfo = "";
		try{
			userinfo = visualService.showEuipmentpersonPic(id);
			if (!userinfo.equals("")){
				out.print(userinfo);
			}
			else{
				String nophotopath = PubMethod.GetWebPath();
				out.print("-1,"+nophotopath+"/visual/images/nophoto.jpg");
			}
		}catch (Exception e) {
			out.print("error");
			e.printStackTrace();
		}
	}
	
	//返回设备数据
	public void getEuipmentData() throws IOException{
		PrintWriter out = PubMethod.GetPrintWriter();
		String id = getRequest().getParameter("id");
		String datainfo = "";
		try{
			datainfo = visualService.getEuipmentData(id);
			out.print(datainfo);
		}catch (Exception e) {
			out.print("error");
			e.printStackTrace();
		}
	}
	
	//返回设备数据
	public void getEuipmentTask() throws IOException{
		PrintWriter out = PubMethod.GetPrintWriter();
		String id = getRequest().getParameter("id");
		String taskinfo = "";
		try{
			taskinfo = visualService.getEuipmentTask(id);
			out.print(taskinfo);
		}catch (Exception e) {
			out.print("error");
			e.printStackTrace();
		}
	}
	
	public String queryVisualById(){
		String id = getRequest().getParameter("id");
		try {
			visualEntity = visualService.GetVisualById(Long.parseLong(id));
			
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "update";
	}
	
	public void editVisual() throws IOException, NumberFormatException, DaoException{
		PrintWriter out = getResponse().getWriter();
		try{
			String address = visualEntity.getPicaddress();
			visualEntity.setId(Long.parseLong(visualid));
			if (picfile!=null){
				ActionContext ac = ActionContext.getContext();
		        ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
				FileInputStream fis = new FileInputStream(picfile); 
				String url = sc.getRealPath("/") + File.separator + "visual" + File.separator + "picfile" + File.separator;
				address = PubMethod.GetTimerName()+".jpg";
				FileOutputStream fos = new FileOutputStream(url+address); 
				byte[] buffer = new byte[1024]; 
				int len = 0; 
				while ((len = fis.read(buffer)) > 0) 
				{ 
					fos.write(buffer, 0, len);
				} 
				fos.close();
				fis.close();
				visualEntity.setPicaddress(address);
			}
			visualService.update(visualEntity);
			out.print("{\"result\":\"success\"}");
		}catch (Exception e) {
			out.print("{\"result\":\"error\"}");
			e.printStackTrace();
		}
	}
	
	
	public void delVisualById() throws IOException
	{
		PrintWriter out = getResponse().getWriter();
		try{
			String ids = getRequest().getParameter("ids");
			String haveSonSql = "select t.id from SYS_VISUALINFO t where t.parentid ='"+ids+"'";
			List list = visualService.findAllBySql2(haveSonSql);
			if(list.size()>0){
				out.print("{\"result\":\"dontDel\"}");
				return;
			}else{
				visualService.delVisuals(ids);
				out.print("{\"result\":\"success\"}");
			}
		}catch (Exception e) {
			out.print("{\"result\":\"error\"}");
		}
	}
	
	public String initVisual() throws DaoException, IOException
	{
		String id = this.getRequest().getParameter("id");
		visualEntity = visualService.GetVisualById(Long.parseLong(id));
		String fileName = visualEntity.getFilename();
		if (fileName==null || fileName.equals("")){
			visualEntity.setFilename("D0000000040.xml");
		}
		getRequest().setAttribute("visualId", id);
		return "designadd";
	}
	
	public String viewVisual() throws DaoException, IOException
	{
		String id = this.getRequest().getParameter("id");
		visualEntity = visualService.GetVisualById(Long.parseLong(id));
		String fileName = visualEntity.getFilename();
		if (fileName==null || fileName.equals("")){
			visualEntity.setFilename("D0000000040.xml");
		}
		return "designview";
	}

	public void SaveXml()
	{
		try{
			HttpServletRequest request = this.getRequest();
			PrintWriter out = PubMethod.GetPrintWriter();
			String visualid = request.getParameter("visualid");
			if (visualid!=null&&!visualid.equals(""))
			{
				VisualInfo entity = visualService.GetVisualById(Long.parseLong(visualid));
				String fileName= entity.getFilename();
				String filePath = "";
				if (fileName==null||fileName.equals("")){
				    fileName= PubMethod.GetTimerName();
					String pathUrl = PubMethod.GetWebPath();
				    filePath = pathUrl+"\\visual\\data\\"+fileName+".xml";
					PubMethod.SaveSampleStreamFile(filePath);
					entity.setFilename(fileName+".xml");
					visualService.update(entity);
				}
				else{
					String pathUrl = PubMethod.GetWebPath();
					filePath = pathUrl+"\\visual\\data\\"+fileName;
					PubMethod.SaveSampleStreamFile(filePath);
				}
			}
			out.print(java.net.URLDecoder.decode("操作成功！","UTF-8"));
		}
		catch(Exception exp)
		{
			exp.printStackTrace();
		}
	}
	
	public void SaveXmlChild()
	{
		try{
			HttpServletRequest request = this.getRequest();
			PrintWriter out = PubMethod.GetPrintWriter();
			String fileName= PubMethod.GetTimerName();
			String pathUrl = PubMethod.GetWebPath();
			String filePath = pathUrl+"\\resources\\FlowManage\\data\\"+fileName+".xml";
			PubMethod.SaveSampleStreamFile(filePath);
			
			out.print(fileName+".xml");
		}
		catch(Exception exp)
		{
			exp.printStackTrace();
		}
	}
	
	
	public void getPersenTree(){
		PrintWriter out = PubMethod.GetPrintWriter();
		String childId = getRequest().getParameter("id");
		Map filterMap = getPagerMap();
		if(null!=childId&&!"".equals(childId))
			filterMap.put("childId", childId);
		PageResult result= visualService.GetVisualList(filterMap);
		String jsonStr = getPersonJson((List<Object>) result.getData());
		out.print(jsonStr);
	}
	
	private String getPersonJson(List<Object> pers) {
		StringBuilder JSONStr = new StringBuilder();
		JSONStr.append("[");
		for (Object obj : pers) {
			Object []objs=(Object [])obj;
			Long childrenNum = objs[0]==null?0l:Long.parseLong(objs[0].toString());
			String icon = childrenNum > 0 ? "folder" : "file";
			String parentid = objs[4] == null ? "" : objs[4].toString();
			JSONStr.append("{\"text\":\"" + objs[1] + "\",\"id\":\"" + objs[0] + "\",\"name\":\"" + objs[1] + "\",\"pId\":\"" + parentid + "\"," +
					"\"childrennum\":\"" + childrenNum + "\",\"leaf\":" + (childrenNum == 0) + ",\"cls\":\"" + icon + "\"},");
		}
		int hasN = JSONStr.lastIndexOf(",");
		if (hasN > 0) {
			JSONStr.deleteCharAt(JSONStr.lastIndexOf(","));
		}
		JSONStr.append("]");
		return JSONStr.toString();
	}
	
	/**
	 * 楼层管理树结构
	 * @return
	 */
	public String getFloorinfotree() throws ServiceException{
		List findOrgB = visualService.getFloor1();
		List findOrgF = visualService.getFloor2();
		List findOrgR = visualService.getFloor3();
		String[] viewArray={"id","name","pId","type"};
		Iterator it = findOrgB.iterator();
		Iterator it2 = findOrgF.iterator();
		Iterator it3 = findOrgR.iterator();
		JSONObject jso=null;
		JSONObject jso2=null;
		JSONObject jso3=null;
		String treeNode="";
		String treeNode2="";
		String treeNode3="";
		while (it.hasNext()) { 
			Object[] objlist = (Object[]) it.next();
			jso=getColumnValue(objlist,viewArray);
			if(jso!=null){
				
				if(treeNode!=""){
					treeNode+=jso+",";
				}else{
					treeNode=""+jso+",";
				}
			}else{
				treeNode="";
			}
			
		} 
		while (it2.hasNext()) { 
			Object[] objlist = (Object[]) it2.next();
			jso2=getColumnValue(objlist,viewArray);
			if(jso2!=null){
				
				if(treeNode2!=""){
					treeNode2+=jso2+",";
				}else{
					treeNode2=""+jso2+",";
				}
			}else{
				treeNode2="";
			}
			
		} 
		while (it3.hasNext()) { 
			Object[] objlist = (Object[]) it3.next();
			jso3=getColumnValue(objlist,viewArray);
			if(jso3!=null){
				
				if(treeNode3!=""){
					treeNode3+=jso3+",";
				}else{
					treeNode3=""+jso3+",";
				}
			}else{
				treeNode3="";
			}
			
		} 
		StringBuffer treeNodes=new StringBuffer();
		treeNodes.append("[");	
		if(!"".equals(treeNode)){
			treeNodes.append(treeNode.substring(0,treeNode.length()-1));
		}
		if(!"".equals(treeNode2)){
			treeNodes.append(",");
			treeNodes.append(treeNode2.substring(0,treeNode2.length()-1));
		}
		if(!"".equals(treeNode3)){
			treeNodes.append(",");
			treeNodes.append(treeNode3.substring(0,treeNode3.length()-1));
		}
		treeNodes.append("]");	
		return treeNodes.toString();
		
	}
	
	public VisualService getVisualService() {
		return visualService;
	}

	public void setVisualService(VisualService visualService) {
		this.visualService = visualService;
	}

	public VisualInfo getVisualEntity() {
		return visualEntity;
	}

	public void setVisualEntity(VisualInfo visualEntity) {
		this.visualEntity = visualEntity;
	}

	public File getPicfile() {
		return picfile;
	}

	public void setPicfile(File picfile) {
		this.picfile = picfile;
	}

}
